<template>
  <n-grid cols="2 s:2 m:2 l:3 xl:3 2xl:3" responsive="screen">
    <n-grid-item>
      <n-form :label-width="80" :model="formValue" :rules="rules" ref="formRef">
        <n-spin :show="spinShow">
          <n-grid :cols="24" :x-gap="24">
            <n-form-item-gi :span="24" label="头像" path="avatar">
              <BasicUpload :action="`${uploadUrl}/moss-cloud-resource/resource/uploadFile`" :headers="uploadHeaders"
                :data="{ type: 0 }" name="file" :width="100" :height="100" @upload-change="uploadAvatar"
                v-model:value="userAvatar" :maxNumber="1" helpText="单个文件不超过2MB，最多只能上传1个文件" />
            </n-form-item-gi>
            <n-form-item-gi :span="12" label="姓名" path="name">
              <n-input v-model:value="formValue.name" placeholder="请输入昵称" />
            </n-form-item-gi>
            <n-form-item-gi :span="12" label="邮箱" path="email">
              <n-input placeholder="请输入邮箱" v-model:value="formValue.email" />
            </n-form-item-gi>
            <n-form-item-gi :span="12" label="联系电话" path="mobile">
              <n-input placeholder="请输入联系电话" v-model:value="formValue.mobile" />
            </n-form-item-gi>
            <n-form-item-gi :span="12" label="性别" path="sex">
              <n-select v-model:value="formValue.sex" filterable placeholder="请选择性别" :options="sexOptions" />
            </n-form-item-gi>
            <n-form-item-gi :span="24" label="生日" path="pickerDate">
              <n-date-picker style="width: 100%;" v-model:value="formValue.pickerDate" type="date" />
            </n-form-item-gi>
            <n-form-item-gi :span="24" label="简介" path="description">
              <n-input v-model:value="formValue.description" type="textarea" placeholder="请输入简介" />
            </n-form-item-gi>
          </n-grid>
        </n-spin>
        <div>
          <n-space>
            <n-button type="primary" :loading="btnLoading" @click="formSubmit">更新基本信息</n-button>
          </n-space>
        </div>
      </n-form>
    </n-grid-item>
  </n-grid>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue';
import { useMessage } from 'naive-ui';
import { currentUser, updateSelf } from '@/api/system/user';
import { dictGroup } from '@/api/system/dict';
import { useGlobSetting } from '@/hooks/setting';
import { useUser } from '@/store/modules/user';
import { formatToDate } from '@/utils/dateUtil';
import { ResultEnum } from '@/enums/httpEnum';
const sexOptions = ref([]);
const globSetting = useGlobSetting();
const { uploadUrl } = globSetting;
const userStore = useUser();
const userAvatar: any = ref([]);
const btnLoading = ref<boolean>(false);
const spinShow = ref<boolean>(false);
const rules = {
  name: {
    required: true,
    message: '请输入昵称',
    trigger: 'blur',
  },
  email: [
    {
      required: true,
      trigger: ['blur', 'input'],
      message: '请输入邮箱',
    },
    { pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/, trigger: ['blur', 'input'], message: '请输入正确的邮箱' },
  ],
  mobile: [
    {
      required: true,
      trigger: ['blur', 'input'],
      message: '请输入手机号',
    },
    { pattern: /^1[3456789]\d{9}$/, trigger: ['blur', 'input'], message: '请输入正确的手机号' },
  ],
  sex: {
    type: 'number',
    required: true,
    message: '请输选择性别',
    trigger: 'blur',
  },
  pickerDate: {
    type: 'date',
    required: true,
    message: '请选择生日',
    trigger: 'blur',
  },
};
const formRef: any = ref(null);
const message = useMessage();
const uploadHeaders = reactive({
  timestamp: new Date().getTime(),
  Authorization: 'Bearer ' + userStore.getToken,
});
const defaultValueRef = () => ({
  /*** 用户姓名*/
  name: '',
  /*** 用户手机*/
  mobile: '',
  /*** 用户邮箱*/
  email: '',
  /*** 用户头像*/
  avatar: '',
  /*** 用户性别*/
  sex: 0,
  /** 生日*/
  birthday: '',
  /** 简介*/
  description: '',
  pickerDate: null,
})
let formValue = reactive(defaultValueRef());
async function getUserInfo() {
  spinShow.value = true;
  const user = await currentUser({});
  formValue = Object.assign(formValue, user, { pickerDate: Date.parse(user.birthday) });
  userAvatar.value = user.avatar ? [user.avatar] : [];
  spinShow.value = false;
}
/**
 * 头像上传
 */
function uploadAvatar(list: string[]) {
  userAvatar.value = list;
  formValue.avatar = list[0];
}
function formSubmit() {
  formRef.value.validate(async (errors) => {
    if (!errors) {
      btnLoading.value = true;
      if (formValue.pickerDate !== null) {
        formValue.birthday = formatToDate(new Date(formValue.pickerDate));
      }
      const data = await updateSelf(formValue);
      if (data.code !== ResultEnum.SUCCESS) {
        const resultMsg = data.data ? data.data : '';
        message.error(data.msg + '-' + resultMsg);
        btnLoading.value = false
      }
      if (data.code === ResultEnum.SUCCESS) {
        message.success(data.msg);
        btnLoading.value = false;
        getUserInfo();
      }
    } else {
      message.error('验证失败，请填写完整信息');
    }
  });
}
/**
 * 性别
 */
async function getSexOptions() {
  const data = await dictGroup({ dictGroup: 'user_sex' });
  const arry = data.map(item => ({ label: item.dictName, value: parseInt(item.dictValue) }));
  sexOptions.value = arry;
}
onMounted(() => {
  getUserInfo();
  getSexOptions();
})
</script>
